package com.wpen.unit.core;

import java.util.concurrent.TimeUnit;

import com.wpen.unit.core.service.DependonScheduleHandler;
import org.springframework.beans.factory.DisposableBean;

import com.wpen.unit.utils.SpringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 依赖调度
 * 
 * @author Wang Peng
 * @date 2022-12-06
 */
@Slf4j
public class DependonScheduleWorker extends ZyxWorker implements DisposableBean {
    private static final DependonScheduleWorker instance = new DependonScheduleWorker();

    private DependonScheduleWorker() {
    }

    public static DependonScheduleWorker getInstance() {
        return instance;
    }

    /* 循环读取间隔时间，扫描库的间隔时间，单位毫秒 */
    private final long loopRead = 30 * 1000;

    private Thread dependObserver;
    private volatile boolean observerRunning = true;

    public void start() {
        log.info(this.getClass().getName() + " start...");

        dependObserver = new Thread(new Runnable() {
            // 常驻在线子线程
            @Override
            public void run() {
                // 检测是否启动完成
                checkAppStarted();
                // 批次扫描线程
                while (observerRunning) {
                    long start = System.currentTimeMillis();
                    try {
                        DependonScheduleHandler scheduleHandler = SpringUtil.getBean(DependonScheduleHandler.class);
                        scheduleHandler.scheduleHandle();
                    } catch (Exception e) {
                        log.error("dependObserverThread Exception>" + e.getMessage(), e);
                    } finally {
                        try {
                            long cost = System.currentTimeMillis() - start;
                            TimeUnit.MILLISECONDS.sleep(loopRead - cost);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        dependObserver.setDaemon(true);
        dependObserver.setName("schedule-depend-observer");
        dependObserver.start();
        log.info(dependObserver.getName() + " running...");
    }

    public void destroy() {
        observerRunning = false;
        log.info(this.getClass().getName() + " bye..");
    }

}
